package com.zhika.zishi.activity;

import android.app.Fragment;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zhika.zishi.MyApplication;
import com.zhika.zishi.constant.InternetConstant;
import com.zhika.zishi.db.OperateDb;
import com.zhika.zishi.db.datas.UserData;
import com.zhika.zishi.fragments.BackHandlerFragment;
import com.zhika.zishi.fragments.login.EntryFragment;
import com.zhika.zishi.fragments.login.LoginFragment;
import com.zhika.zishi.fragments.login.RegisterFragment;
import com.zhika.zishi.fragments.login.RegisterUserFragment;
import com.zhika.zishi.fragments.login.ResetPasswordFragment;
import com.zhika.zishi.fragments.login.SelectHobbyFragment;
import com.zhika.zishi.interfaces.BackPressedInterface;
import com.zhika.zishi.util.LogUtil;

import org.apache.http.Header;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import org.json.JSONStringer;

import java.util.ArrayList;


/**
 * Created by shi-02 on 2015/5/2.
 * 登录、注册系列的activity
 */
public class MainActivity extends BaseFragmentActivity implements EntryFragment.OnEntryListener,
        LoginFragment.OnLoginListener, RegisterFragment.OnRegisterListener, SelectHobbyFragment.OnSelectHobbyListener,
        BackPressedInterface {

    private final String TAG = "MainActivity";

    //注册
    private RegisterFragment registerFragment;

    //登录
    private LoginFragment loginFragment;

    //进入页
    private EntryFragment entryFragment;

    //忘记密码
    private ResetPasswordFragment resetPasswordFragment;

    //选择个人爱好
    private SelectHobbyFragment selectHobbyFragment;

    //选择关注用户
    private RegisterUserFragment registerUserFragment;

    //登录返回给handler的
    private static final int LOGIN = 1;

    //自动登录--handler
    private static final int AUTO_LOGIN = 2;

    //操作数据库的对象
    private OperateDb operateDb;

    //有自定义物理back的事件的fragment
    private BackHandlerFragment backHandlerFragment;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOGIN:

                    //登录成功
                    if (msg.arg1 == 1) {
                        Intent intent = new Intent(MainActivity.this, RecommendHomepageActivity.class);
                        startActivity(intent);
                    } else {
                        String errorStr = (String) msg.obj;
                        showToast("登录失败:"+errorStr);
                    }
                    break;
                case AUTO_LOGIN:
                    if (msg.arg1 == 1) {
                        Intent intent = new Intent(MainActivity.this, RecommendHomepageActivity.class);
                        startActivity(intent);
                    }
                    break;
            }
        }
    };

    @Override
    public Fragment createFragment() {

        Intent intent = getIntent();

        //如果是进入应用
        if (intent.getStringExtra("intent") == null || intent.getStringExtra("intent").equals("")) {

            if (entryFragment == null) {
                entryFragment = new EntryFragment();
            }

            return entryFragment;
        }

        //这是退出应用时
        String type = intent.getStringExtra("intent");
        if (type.equals("login")) {
            if (loginFragment == null) {
                loginFragment = new LoginFragment();
            }
            return loginFragment;
        }
        return null;
    }

    @Override
    public void doThing() {

        //实例化数据库的操作对象
        operateDb = new OperateDb(MainActivity.this);

        if (operateDb.queryUser().size()>0){
            autoLogin();
        }
    }

    @Override
    public void entryLoginListener() {
        if (loginFragment == null) {
            loginFragment = new LoginFragment();
        }

        startFragment(entryFragment, loginFragment);
    }

    @Override
    public void setSelectedFragment(BackHandlerFragment selectedFragment) {
        this.backHandlerFragment= selectedFragment;
    }

    @Override
    public void entryBrowseListener() {

        //启动主页面
        Intent intent = new Intent(MainActivity.this,RecommendHomepageActivity.class);
        startActivity(intent);
    }

    @Override
    public void login(String user, String password) {

        String url = InternetConstant.SERVER_ADDRESS + InternetConstant.LOGIN;
        LogUtil.e(TAG, "登录：url=" + url);

        try {

//            {"telephone":"1373******","passwd":"test","deviceTag":"KHASUIQ23JKHAQ"}
            JSONStringer stringer = new JSONStringer().object()
                    .key("telephone").value(user)
                    .key("passwd").value(password)
                    .key("deviceTag").value(MyApplication.device_id)
                    .endObject();

            StringEntity entity = new StringEntity(stringer.toString(), HTTP.UTF_8);
            LogUtil.e(TAG, "登录：entry=" + entity);

            MyApplication.asyncHttpClient.post(MainActivity.this, url, entity, InternetConstant.CONTENT_TYPE, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    LogUtil.e(TAG, "登录-成功码：i=" + i);
                    String jsonData = new String(bytes);
                    LogUtil.e(TAG, "登录-返回的数据：" + jsonData);

                    //解析json数据
                    parseLoginJson(jsonData);
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                    LogUtil.e(TAG, "登录-错误码：i=" + i);
                    throwable.printStackTrace();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
//        Intent intent = new Intent(this, HomepageActivity.class);
//        startActivity(intent);
    }

    @Override
    public void loginRegisterListener() {

        if (registerFragment == null) {
            registerFragment = new RegisterFragment();
        }

        startFragment(loginFragment, registerFragment);

    }

    @Override
    public void loginForgetPassword() {

        if (resetPasswordFragment == null) {
            resetPasswordFragment = new ResetPasswordFragment();
        }

        startFragment(loginFragment, resetPasswordFragment);
    }

    @Override
    public void registerLogin() {
        super.onBackPressed();
    }

    @Override
    public void register() {

        if (selectHobbyFragment == null) {
            selectHobbyFragment = new SelectHobbyFragment();
        }

        startFragment(registerFragment, selectHobbyFragment);
    }

    @Override
    public void selectHobbySure(String likeStrategy) {
        if (registerUserFragment == null) {
            registerUserFragment = new RegisterUserFragment();
        }

        startFragment(selectHobbyFragment, registerUserFragment);
    }

    /**
     * 解析登录返回的json数据
     *
     * @param jsonData
     */
    private void parseLoginJson(String jsonData) {
        if (jsonData == null || jsonData.equals("")) {
            showToast("返回的数据为空");
        } else {
            try {
                JSONObject jsonObject = new JSONObject(jsonData);
                boolean b = jsonObject.getBoolean("success");
                Message message = Message.obtain();
                message.what = LOGIN;

                //登录成功
                if (b) {
                    message.arg1 = 1;
                    JSONObject paramObject = jsonObject.getJSONObject("param");
                    UserData userData = new UserData();

                    long uid = paramObject.getLong("uid");
                    userData.setUserId(uid);

                    userData.setNickname(paramObject.getString("nickname"));

                    String token = paramObject.getString("token");
                    userData.setUserToken(token);

                    //1 -- 处于登录状态，2-- 退出状态
                    userData.setIsLogin(1);

                    //设置当前登录用户的id和token
                    MyApplication.userId = uid;
                    MyApplication.token = token;

                    //更新用户的token
                    operateDb.updateUserToken(userData);

                }
                //登录失败
                else {
                    message.arg1 = 2;
                    String errorStr = jsonObject.getString("error");
                    message.obj = errorStr;
                }
                handler.sendMessage(message);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 吐丝
     *
     * @param msg
     */
    private void showToast(String msg) {
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 自动登录
     */
    private void autoLogin() {
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();

        String url = InternetConstant.SERVER_ADDRESS + InternetConstant.AUTO_LOGIN;
        Log.e(TAG, "自动登录url:" + url);

        ArrayList<UserData> userList = MyApplication.operateDb.queryUser();

        for (int i = 0; i < userList.size(); i++) {
            if (userList.get(i).getIsLogin() == 1) {

                // uid= token= deviceTag=
                RequestParams params = new RequestParams();
                params.put("uid", userList.get(i).getUserId());
                params.put("token", userList.get(i).getUserToken());
                params.put("deviceTag", MyApplication.device_id);

                asyncHttpClient.post(MainActivity.this, url, params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
                        String jsonData = new String(bytes);
                        LogUtil.e(TAG, "自动登录-成功码：code=" + i + ";返回json:" + jsonData);
                        parseAutoLoginJson(jsonData);
                    }

                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                        LogUtil.e(TAG, "自动登录-错误码：code=" + i);
                        throwable.printStackTrace();
                    }
                });

                break;
            }
        }
    }

    /**
     * 解析自动登录返回的数据
     * @param jsonData
     */
    private void parseAutoLoginJson(String jsonData) {
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            boolean isSuccess = jsonObject.getBoolean("success");
            Message message = Message.obtain();
            message.what = AUTO_LOGIN;

            //自动登录成功
            if (isSuccess) {
                message.arg1 = 1;
            }
            //自动登录失败
            else {
                message.arg1 = 2;
            }
            handler.sendMessage(message);

            JSONObject paramObject = jsonObject.getJSONObject("param");
            String token = paramObject.getString("token");
            long uid = paramObject.getLong("uid");
            String nickname = paramObject.getString("nickname");

            UserData userData = new UserData();
            userData.setIsLogin(1);
            userData.setUserToken(token);
            userData.setNickname(nickname);
            userData.setUserId(uid);

            //重置uid和token
            MyApplication.userId = uid;
            MyApplication.token = token;

            //更新表中的token,
            operateDb.updateUserToken(userData);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        if(backHandlerFragment == null || !backHandlerFragment.onBackPressed()){
            if(getFragmentManager().getBackStackEntryCount() == 0){
                super.onBackPressed();
            }else{
                getFragmentManager().popBackStack();
            }
        }
    }
}
